<template>
	<div v-if="show" class="numcard numcardItem1">
		<span class="real-time-num gsapNum" ref="number">{{ formattedNumber }}{{unit}}</span>
	</div>
</template>

<script>
	import gsap from 'gsap';

	export default {
		data() {
			return {
				rawNumber: 0, // 更改为rawNumber，存储实际数字值
				show: true,
				showComma: false, // 是否显示千分位逗号
			};
		},
		props: {
			number: {
				type: [Number, String],
				default () {
					return 0;
				},
			},
			unit: { // 控制单位显示
				type: String,
				default: ''
			},
			comma: { // 通过props控制是否显示千分位
				type: Boolean,
				default: false
			},
			delay: {
				type: [Number, String],
				default () {
					return 0;
				},
			},
		},
		computed: {
			formattedNumber() {
				return this.rawNumber;
			},
			currentNumber: {
				get() {
					return this.rawNumber;
				},
				set(value) {
					this.rawNumber = value;
				}
			}
		},
		watch: {
			number(newVal) {
				if (this.show) {
					this.$nextTick(() => {
						this.currentNumber = 0
						this.animateNumber(this.currentNumber, newVal);
					});
				}
			},
			show() {
				this.$nextTick(() => {
					this.currentNumber = 0
					this.animateNumber(this.currentNumber, this.number);
				});
			},
			comma(newVal) {
				this.showComma = newVal; // 设置是否显示千分位
			}
		},
		methods: {
			animateNumber(start, end) {
				// 计算原始数字的小数位数
				let decimalPlaces = (end.toString().split('.')[1] || '').length;

				gsap.to(this, {
					currentNumber: end,
					duration: 2,
					delay: parseFloat(this.delay),
					ease: 'power1.out',
					onUpdate: () => {
						// 保持相同的小数位数
						this.currentNumber = parseFloat(this.currentNumber.toFixed(decimalPlaces));
					},
				});
			},
		},
		mounted() {
			this.showComma = this.comma;
			this.showDecimal = this.decimal; // 初始化显示小数的设置
			if (this.show) {
				this.currentNumber = 0
				this.animateNumber(this.currentNumber, this.number);
			}
		},
	};
</script>

<style lang="scss">
	.numcardItem1 {
		.real-time-num {
			width: auto !important;
			font-family: 'DIN-Bold';
			font-weight: bold;
			background: linear-gradient(180deg, #00C2FF 42.52%, #FFFFFF 70.97%);
			-webkit-background-clip: text;
			-moz-background-clip: text;
			background-clip: text;
			color: transparent;
			font-style: normal;
		}
	}

	@keyframes slideUp {
		from {
			transform: translateY(100%);
			opacity: 0;
		}

		to {
			transform: translateY(0);
			opacity: 1;
		}
	}
</style>